import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { ArrowLeft, Trophy, Calendar, Clock, Users, Target, RefreshCw, Play, Pause, CheckCircle, Sword, Shield, ChevronLeft, ChevronRight } from "lucide-react"
import { LeagueMatch } from '@/types/dota'
import { useLeagueData } from '@/hooks/useLeagueData'

interface LeagueMatchesProps {
  leagueId: number
  onBack: () => void
  onMatchClick?: (matchId: number) => void
}

function LeagueMatches({ leagueId, onBack, onMatchClick }: LeagueMatchesProps) {
  const [pageSize] = useState(20)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalMatches, setTotalMatches] = useState(0)
  const [autoUpdateEnabled, setAutoUpdateEnabled] = useState(false)
  const [isCheckingUpdates, setIsCheckingUpdates] = useState(false)

  const {
    leagueMatches,
    leagueDetail,
    leagueStats,
    loading,
    error,
    lastUpdateCheck,
    loadLeagueMatches,
    loadLeagueDetail,
    loadLeagueStats,
    checkForUpdates,
    enableAutoUpdate,
    disableAutoUpdate,
    totalMatchCount
  } = useLeagueData(leagueId)

  // 初始加载
  useEffect(() => {
    console.log('LeagueMatches - 初始加载，参数:', { leagueId, currentPage, pageSize })
    loadLeagueMatches(currentPage - 1, pageSize) // API使用0基索引，UI使用1基索引
    
    // 如果没有联赛详情，也加载一下
    if (!leagueDetail) {
      loadLeagueDetail()
    }
    
    // 加载联赛统计信息
    if (!leagueStats) {
      loadLeagueStats()
    }
  }, [leagueId, currentPage, loadLeagueMatches, pageSize, leagueDetail, loadLeagueDetail, leagueStats, loadLeagueStats])

  // 更新总比赛数
  useEffect(() => {
    console.log('LeagueMatches - totalMatchCount:', totalMatchCount)
    console.log('LeagueMatches - leagueDetail.stats?.matchCount:', leagueDetail?.stats?.matchCount)
    console.log('LeagueMatches - leagueStats?.totalMatches:', leagueStats?.totalMatches)
    
    // 优先使用联赛统计中的总场数
    if (leagueStats?.totalMatches && leagueStats.totalMatches > 0) {
      setTotalMatches(leagueStats.totalMatches)
      console.log('LeagueMatches - 使用联赛统计中的总场数:', leagueStats.totalMatches)
    } else if (leagueDetail?.stats?.matchCount && leagueDetail.stats.matchCount > 0) {
      setTotalMatches(leagueDetail.stats.matchCount)
      console.log('LeagueMatches - 使用联赛详情中的总场数:', leagueDetail.stats.matchCount)
    } else if (totalMatchCount !== null && totalMatchCount > 0) {
      setTotalMatches(totalMatchCount)
      console.log('LeagueMatches - 使用API获取的总数:', totalMatchCount)
    }
  }, [totalMatchCount, leagueDetail, leagueStats])

  // 清理自动更新
  useEffect(() => {
    return () => {
      if (autoUpdateEnabled) {
        disableAutoUpdate()
      }
    }
  }, [autoUpdateEnabled, disableAutoUpdate])

  // 手动检查更新
  const handleCheckUpdates = async () => {
    setIsCheckingUpdates(true)
    try {
      await checkForUpdates()
    } finally {
      setIsCheckingUpdates(false)
    }
  }

  // 切换自动更新
  const handleToggleAutoUpdate = () => {
    if (autoUpdateEnabled) {
      disableAutoUpdate()
      setAutoUpdateEnabled(false)
    } else {
      enableAutoUpdate(3 * 60 * 1000)
      setAutoUpdateEnabled(true)
    }
  }

  // 格式化最后更新检查时间
  const formatLastUpdateCheck = (timestamp?: number) => {
    if (!timestamp) return '从未检查'
    const now = Date.now()
    const diff = now - timestamp
    const minutes = Math.floor(diff / (1000 * 60))
    
    if (minutes < 1) return '刚刚检查'
    if (minutes < 60) return `${minutes}分钟前`
    const hours = Math.floor(minutes / 60)
    if (hours < 24) return `${hours}小时前`
    const days = Math.floor(hours / 24)
    return `${days}天前`
  }

  // 分页导航函数
  const goToPage = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page)
    }
  }

  const goToPrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1)
    }
  }

  const goToNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1)
    }
  }

  // 计算总页数
  const totalPages = Math.max(1, Math.ceil(totalMatches / pageSize))

  const formatDate = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    })
  }

  const formatTime = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const formatDuration = (seconds: number) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }

  const getMatchResult = (match: LeagueMatch) => {
    if (match.radiant_win === null || match.radiant_win === undefined) return '进行中'
    return match.radiant_win ? '天辉胜利' : '夜魇胜利'
  }

  const getResultColor = (match: LeagueMatch) => {
    if (match.radiant_win === null || match.radiant_win === undefined) return 'bg-blue-500'
    return match.radiant_win ? 'bg-green-500' : 'bg-red-500'
  }

  if (loading.matches) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
          <h1 className="text-2xl font-bold">联赛比赛</h1>
        </div>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-center py-12">
              <div className="flex items-center gap-3">
                <div className="w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
                <span className="text-gray-600">正在加载比赛数据...</span>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  if (error.matches) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
          <h1 className="text-2xl font-bold">联赛比赛</h1>
        </div>
        
        <Card>
          <CardContent className="p-6">
            <div className="text-center py-12">
              <div className="text-red-500 mb-4">
                <Target className="w-12 h-12 mx-auto mb-2" />
                <p className="text-lg font-medium">加载失败</p>
                <p className="text-sm text-gray-600 mt-1">{error.matches}</p>
              </div>
              <Button onClick={() => loadLeagueMatches(currentPage, pageSize)} variant="outline">
                <RefreshCw className="w-4 h-4 mr-2" />
                重试
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 头部导航 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
          <h1 className="text-2xl font-bold">联赛比赛</h1>
        </div>
        
        <div className="flex items-center gap-3">
          <div className="text-sm text-gray-600">
            最后检查: {formatLastUpdateCheck(lastUpdateCheck)}
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={handleCheckUpdates}
            disabled={isCheckingUpdates}
          >
            {isCheckingUpdates ? (
              <>
                <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                检查中...
              </>
            ) : (
              <>
                <RefreshCw className="w-4 h-4 mr-2" />
                检查更新
              </>
            )}
          </Button>
          <Button
            variant={autoUpdateEnabled ? "default" : "outline"}
            size="sm"
            onClick={handleToggleAutoUpdate}
          >
            {autoUpdateEnabled ? (
              <>
                <Pause className="w-4 h-4 mr-2" />
                停止自动更新
              </>
            ) : (
              <>
                <Play className="w-4 h-4 mr-2" />
                开启自动更新
              </>
            )}
          </Button>
        </div>
      </div>

      {/* 比赛统计 */}
      {leagueMatches && leagueMatches.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Trophy className="w-5 h-5" />
              比赛统计
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-blue-50 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{totalMatches}</div>
                <div className="text-sm text-gray-600">总比赛数</div>
              </div>
              <div className="text-center p-4 bg-green-50 rounded-lg">
                <div className="text-2xl font-bold text-green-600">
                  {leagueStats ? leagueStats.radiantWins : (leagueMatches.filter(match => match.radiant_win === true).length)}
                </div>
                <div className="text-sm text-gray-600">天辉胜利</div>
              </div>
              <div className="text-center p-4 bg-red-50 rounded-lg">
                <div className="text-2xl font-bold text-red-600">
                  {leagueStats ? leagueStats.direWins : (leagueMatches.filter(match => match.radiant_win === false).length)}
                </div>
                <div className="text-sm text-gray-600">夜魇胜利</div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 比赛列表 */}
      <Card>
        <CardHeader>
          <CardTitle>比赛列表</CardTitle>
          <CardDescription>
            第 {currentPage} 页，共 {totalPages} 页 | 每页 {pageSize} 条 | 总计 {totalMatches} 场比赛
          </CardDescription>
        </CardHeader>
        <CardContent>
          {!leagueMatches || leagueMatches.length === 0 ? (
            <div className="text-center py-12">
              <Trophy className="w-12 h-12 mx-auto mb-4 text-gray-400" />
              <p className="text-gray-600">暂无比赛数据</p>
            </div>
          ) : (
            <div className="space-y-4">
              {leagueMatches.map((match) => (
                <div
                  key={match.match_id}
                  className="border rounded-lg p-4 hover:bg-muted/50 cursor-pointer transition-colors"
                  onClick={() => onMatchClick?.(match.match_id)}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div className="text-center">
                        <div className="text-sm text-gray-500">比赛 ID</div>
                        <div className="font-mono text-sm">{match.match_id}</div>
                      </div>
                      
                      <Separator orientation="vertical" className="h-12" />
                      
                      <div className="flex items-center gap-3">
                        <div className="text-center">
                          <div className="text-sm text-gray-500 mb-1">日期</div>
                          <div className="flex items-center gap-2 text-sm">
                            <Calendar className="w-4 h-4" />
                            {formatDate(match.start_time)}
                          </div>
                        </div>
                        
                        <div className="text-center">
                          <div className="text-sm text-gray-500 mb-1">时间</div>
                          <div className="flex items-center gap-2 text-sm">
                            <Clock className="w-4 h-4" />
                            {formatTime(match.start_time)}
                          </div>
                        </div>
                        
                        {match.duration && (
                          <div className="text-center">
                            <div className="text-sm text-gray-500 mb-1">时长</div>
                            <div className="text-sm font-mono">
                              {formatDuration(match.duration)}
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                    
                    <div className="flex items-center gap-4">
                      <div className="text-center">
                        <div className="text-sm text-gray-500 mb-1">结果</div>
                        <Badge 
                          className={`${getResultColor(match)} text-white`}
                        >
                          {getMatchResult(match)}
                        </Badge>
                      </div>
                      
                      <div className="flex items-center gap-2">
                        <Sword className="w-4 h-4 text-red-500" />
                        <span className="text-sm">vs</span>
                        <Shield className="w-4 h-4 text-green-500" />
                      </div>
                    </div>
                  </div>
                </div>
              ))}
              
              {/* 分页导航 */}
              <div className="flex items-center justify-between pt-6 border-t border-gray-100">
                <div className="flex items-center gap-2 text-sm text-gray-600">
                  <span>第 {currentPage} 页，共 {totalPages} 页</span>
                </div>
                
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={goToPrevPage}
                    disabled={currentPage === 1}
                    className="h-9 px-3"
                  >
                    <ChevronLeft className="w-4 h-4 mr-1" />
                    上一页
                  </Button>
                  
                  <div className="flex items-center gap-1">
                    {/* 页码按钮 */}
                    {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                      let pageNum;
                      if (totalPages <= 5) {
                        pageNum = i + 1;
                      } else if (currentPage <= 3) {
                        pageNum = i + 1;
                      } else if (currentPage >= totalPages - 2) {
                        pageNum = totalPages - 4 + i;
                      } else {
                        pageNum = currentPage - 2 + i;
                      }
                      
                      return (
                        <Button
                          key={pageNum}
                          variant={currentPage === pageNum ? "default" : "outline"}
                          size="sm"
                          onClick={() => goToPage(pageNum)}
                          className="h-9 w-9 p-0"
                        >
                          {pageNum}
                        </Button>
                      );
                    })}
                  </div>
                  
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={goToNextPage}
                    disabled={currentPage === totalPages}
                    className="h-9 px-3"
                  >
                    下一页
                    <ChevronRight className="w-4 h-4 ml-1" />
                  </Button>
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

export default LeagueMatches